<template>
  <div class="center">
    <createInfo @closeInfo="closeInfo" :FirmwareDate="FirmwareDate" :infoData="infoData" v-if="infoShow" />
    <div v-else>
      <!-- 头部 -->
      <div class="table_header flex flex_bet flex-wrap">
        <div class="table_button">
          <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="btnaddBrand">添加</el-button>
        </div>
        <div class="table_searchs flex felx_align">
          <div class="table_search flex">
            <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
              <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
                <el-option label="用户名" value="1"></el-option>
                <el-option label="sn码" value="2"></el-option>
                <el-option label="mac" value="3"></el-option>
              </el-select>
              <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
            </el-input>
          </div>
          <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
        </div>
      </div>
      <!-- 专题管理table -->
      <el-table stripe :data="brandTable" style="width: 100%" :key="key" border fit highlight-current-row ref="tableDataRef">
        <el-table-column v-if="colData[0].istrue" prop="digits_one" label="第一位数" min-width="80" align="center"></el-table-column>
        <el-table-column v-if="colData[1].istrue" prop="digits_two" label="第二位数" min-width="80" align="center"></el-table-column>
        <el-table-column v-if="colData[2].istrue" prop="digits_there" label="第三/四位数" min-width="100" align="center"></el-table-column>
        <el-table-column v-if="colData[3].istrue" prop="digits_five" label="第五位数" min-width="80" align="center"></el-table-column>
        <el-table-column v-if="colData[4].istrue" prop="name" label="产品型号名" min-width="120" align="center"></el-table-column>
        <el-table-column v-if="colData[5].istrue" prop="digits_str" label="前五位拼接数" min-width="120" align="center"></el-table-column>
        <el-table-column v-if="colData[7].istrue" prop="ean_code" label="EAN商品码" min-width="120" align="center"></el-table-column>
        <el-table-column v-if="colData[8].istrue" prop="username" label="生成者" min-width="120" align="center"></el-table-column>
        <el-table-column v-if="colData[9].istrue" prop="sn_value" label="sn码" min-width="120" align="center">
          <template slot-scope="scope">
            <!-- <el-link @click="getsnGetDigitsFiveDetailed(scope.row.sn_value)">{{scope.row.sn_value}}</el-link> -->
            {{scope.row.sn_value}}
          </template>
        </el-table-column>
        <el-table-column v-if="colData[8].istrue" prop="mac" label="mac地址" min-width="130" align="center"></el-table-column>
        <el-table-column v-if="colData[9].istrue" prop="imei" label="IMEI号" min-width="130" align="center">
          <template slot-scope="scope">
            <p v-html="scope.row.imei.split(/,/g).join(',<br/>')"></p>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[10].istrue" prop="create_time" label="创建时间" min-width="150" align="center">
          <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
        </el-table-column>
        <el-table-column label="操作" min-width="90" align="center">
          <template slot-scope="scope">
            <el-row>
              <el-button size="mini" type="primary" @click="goCreateinfo(scope.row)">详情</el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="paging">
        <el-pagination :current-page.sync="listQuery.startSize" :page-sizes="[10, 50, 100, 200]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" background
          @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
      </div>
    </div>
    <!-- 添加应用专题 -->
    <el-dialog :title="editSubjects ? 'SN生成规则' : '编辑'" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
      <el-form :model="addForm" ref="ruleForm" :rules="rules" class="diolog_adapt">
        <el-form-item label="第一位:" label-width="100px" prop="oneId">
          <el-select v-model="addForm.oneId" placeholder="请选择第一位" class="add_select">
            <el-option v-for="item in oneBox" :key="item.id" :label="`${item.name_code} : ${item.name}`" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="第二位:" label-width="100px" prop="twoId">
          <el-select v-model="addForm.twoId" placeholder="请选择第二位" class="add_select">
            <el-option v-for="item in towBox" :key="item.id" :label="`${item.name_code} : ${item.name}`" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="第三/四位:" label-width="100px" prop="thereId">
          <el-select v-model="addForm.thereId" placeholder="请选择第三/四位" class="add_select" @change="thereSelect">
            <el-option v-for="item in thereBox" :key="item.id" :label="`${item.name_code} : ${item.name}`" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="第五位:" label-width="100px" prop="fiveId">
          <el-select v-model="addForm.fiveId" placeholder="请先选择第三/四位" class="add_select" :disabled="fiveShow">
            <el-option v-for="item in fiveBox" :key="item.id" :label="item.name_code" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年份:" label-width="100px" prop="year">
          <el-date-picker v-model="addForm.year" type="year" placeholder="选择年份" value-format='yyyy'>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="月份:" label-width="100px" prop="month">
          <el-date-picker v-model="addForm.month" type="month" placeholder="选择月份" format="MM" value-format='MM'>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建数量:" label-width="100px" prop="sumCount">
          <el-input v-model="addForm.sumCount" autocomplete="off" placeholder="请输入创建数量" class="add_select"></el-input>
        </el-form-item>
        <el-form-item label="用途:" label-width="100px" prop="purpose">
          <el-input v-model="addForm.purpose" autocomplete="off" placeholder="请输入用途说明" class="add_select"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="mini" round>取 消</el-button>
        <Debounce :time='3000' :isDebounce="2">
          <el-button v-if="editSubjects" type="primary" @click.native="createSns('ruleForm')" size="mini" round>确 定</el-button>
          <el-button v-else type="primary" @click.native="getupdateDigitsFive('ruleForm')" size="mini" round>编辑</el-button>
        </Debounce>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import deleteDialog from "@/components/deleteDialog";
import permission from '@/directive/permission/index.js' // 权限判断指令
import { getCreateDigits, getCreateSn, createSn, getCreateDigitsFive, snGetDigitsFiveDetailed } from "@/api/snControl.js";
import createInfo from '../components/createInfo.vue'
import { mapState } from 'vuex'
export default {
  directives: { permission },
  components: { dynamicTable, deleteDialog, createInfo },
  data() {
    return {
      checkboxVal: ['第一位数', '第二位数', '第三/四位数', '第五位数', '产品型号名', '前五位拼接数','EAN商品码', '生成者', 'sn码', 'mac地址','IMEI号', '生成时间'],
      key: 1,
      colData: [],//动态控制table
      brandTable: [],
      select: "", //搜索条件
      searchTable: "",
      total: 0, //总数量
      //添加按钮控制
      dialogFormVisible: false,
      //编辑按钮控制
      editSubjects: true,
      //编辑专题id
      subjectId: 0,
      listQuery: { startSize: 1, pageSize: 10, username: undefined, sn: undefined, mac: undefined, userId: localStorage.getItem("ID") },
      //添加表单
      addForm: { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), oneId: '', twoId: '', thereId: '', fiveId: '', sumCount: '', year: '', month: '', purpose: '' },
      //下拉选择框
      oneBox: [],
      towBox: [],
      thereBox: [],
      fiveBox: [],
      fiveShow: true,
      rules: {
        oneId: [{ required: true, message: "请选择第一位", trigger: "blur" }],
        twoId: [{ required: true, message: "请选择第二位", trigger: "blur" }],
        thereId: [{ required: true, message: "请选择第三/四位", trigger: "blur" }],
        fiveId: [{ required: true, message: "请选择第五位", trigger: "blur" }],
        sumCount: [{ required: true, message: "请输入创建数量", trigger: "blur" }],
        year: [{ required: true, message: "请选择年份", trigger: "blur" }],
        month: [{ required: true, message: "请选择月份", trigger: "blur" }],
        purpose: [{ required: true, message: "请输入用途说明", trigger: "blur" }],
      },
      infoShow: false,
      infoData: {},
      FirmwareDate: {}
    }
  },
  computed: {
    ...mapState({//获取上传滚动条
      goodsData: state => state.user.progress
    })
  },
  watch: {
    goodsData(val) {
      console.log('进度条',val)
    }
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal);//转为数组对象，好控制table
    this.getCreateSns()
    this.getCreateDigitss(1)
    this.getCreateDigitss(2)
    this.getCreateDigitss(3)
  },
  methods: {
    getsnGetDigitsFiveDetailed(value) {
      snGetDigitsFiveDetailed({ sn: value }).then(res => {
        this.FirmwareDate = res.data
      })
    },
    goCreateinfo(item) {
      this.getsnGetDigitsFiveDetailed(item.sn_value)
      this.infoData = item
      this.infoShow = true
    },
    closeInfo() {
      this.infoShow = false
    },
    //添加SN
    createSns(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          createSn(addForm).then(res => {
            this.$message.success('SN生成成功，请在SN生产记录下载excel文件')
            this.getCreateSns()
            this.dialogFormVisible = false
            //console.log('生成SN成功',res)
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    //第三/第四的change事件
    thereSelect(val) {
      if (val) {
        this.getCreateDigitsFives(val)
        this.fiveShow = false
      } else {
        this.fiveShow = true
      }
    },
    getCreateDigitsFives(id) {
      getCreateDigitsFive({ thereId: id }).then(res => {
        this.fiveBox = res.data
      }).catch(err => {
        this.fiveBox = []
      })
    },
    getCreateSns() {
      getCreateSn(this.listQuery).then(res => {
        this.brandTable = res.data
        this.total = res.total
        console.log('表格数据', res.data)
      }).catch(err => {
        this.brandTable = []
        this.total = 0
      })
    },
    btnaddBrand() {
      this.editSubjects = true
      this.dialogFormVisible = true
    },
    //获取1、2、3位数信息
    getCreateDigitss(type) {
      getCreateDigits({ type: type }).then(res => {
        switch (type) {
          case 1:
            this.oneBox = res.data
            break;
          case 2:
            this.towBox = res.data
            break;
          case 3:
            this.thereBox = res.data
            break;
        }
      }).catch(err => {
        switch (type) {
          case 1:
            this.oneBox = []
            break;
          case 2:
            this.towBox = []
            break;
          case 3:
            this.thereBox = []
            break;
        }
      })
    },
    //分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getCreateSns();
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getCreateSns();
    },
    //搜索,1，专题名称
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.username = this.searchTable
          break;
        case '2':
          this.listQuery.sn = this.searchTable
          break;
        case '3':
          this.listQuery.mac = this.searchTable
          break;
      }
      this.getCreateSns();
    },
    Refresh() {
      this.listQuery = { startSize: 1, pageSize: 10, username: undefined, sn: undefined, mac: undefined, userId: localStorage.getItem("ID") }
      this.getCreateSns()
    },
    //表单关闭事件
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
      })
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    }
  }
}
</script>